package com.example.shushiyunsst.fragment.main.home.child.icon_sst

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.library_common.utils.normalShortToast
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.CMLTransferBean
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.CurrencyTransferJavaParent
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type

class CMLTransferFragment : SimpleListFragment<CMLTransferBean>(), CurrencyTransferLab,
    OnItemChildClickListener {

    companion object {
        fun newInstance(): CMLTransferFragment {
            val args = Bundle()
            val fragment = CMLTransferFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var transferParent: CurrencyTransferJavaParent? = null

    fun setTransferParent(transferParent: CurrencyTransferJavaParent): CMLTransferFragment {
        this.transferParent = transferParent
        return this
    }

    private var currentStatus = 0

    override val title = R.string.cml_str


    override val tokenType = TOKEN_TYPE_CML

    private var uid = ""

    //isShowCmlPub  是否显示发布（+）按钮，1 是；0否
    private var isShowCmlPub = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        isAddDividerItemDecoration = false
    }

    override fun upData() {
        val status = transferParent?.currentStatus ?: R.string.on_sale
        if (status != currentStatus) {
            currentStatus = status
            if (!mSwipeRefreshLayout.isRefreshing) {
                mSwipeRefreshLayout.isRefreshing = true
                onRefresh()
            }
        }
    }

    override fun upListData() {
        if (!mSwipeRefreshLayout.isRefreshing) {
            mSwipeRefreshLayout.isRefreshing = true
            onRefresh()
        }

    }

    override fun getItemLayout(): Int {
        return R.layout.cml_layout_transfer_fragment
    }

    override fun initView(view: View) {
        super.initView(view)
        mAdapter.addChildClickViewIds(R.id.bottomTv, R.id.deleteTv)
        mAdapter.setOnItemChildClickListener(this)
    }

    override fun convertItem(helper: JssBaseViewHolder?, item: CMLTransferBean?) {

        helper?.setText(R.id.name, item?.nickName)
            ?.setImageNetUrl(R.id.icon, item?.userLogo)
            ?.setText(R.id.ratio, "${item?.selledNums} | ${item?.credibility}%")
            ?.setViewVisible(R.id.deleteTv, "${item?.uid}" == uid)
            ?.setViewVisible(R.id.bottomTv, "${item?.uid}" != uid)
            ?.setText(R.id.count, "数量 ${item?.stock} ${item?.tokenType}")
            ?.setText(R.id.singlePrice, "${item?.price}")
            ?.setText(
                R.id.limit,
                "限额 ${item?.tokenType} ${item?.limitMin}-${item?.tokenType} ${item?.limitMax}"
            )
            ?.setText(
                R.id.bottomTv, when (item?.txType) {
                    ICON_TRANSFER_SETTING_BUY -> R.string.buying
                    ICON_TRANSFER_SETTING_SELL -> R.string.on_sale
                    else -> R.string.on_sale
                }
            )
    }

    override fun onResume() {
        super.onResume()
        transferParent?.showSettingBtn(isShowCmlPub)
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        upData()
//        transferParent?.handSettingBtn(tokenType)
        transferParent?.showSettingBtn(isShowCmlPub)
    }

    override fun handMessage(msg: MessageWrap?) {

        if (msg?.message == TO_REFRESH_LIST) {
            upListData()
        }
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(CMLTransferBean::class.java).endSubType().build()
    }

    override fun netRequest() {

//        transferParent?.handSettingBtn(tokenType)
        transferParent?.showSettingBtn(isShowCmlPub)

        uid = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo?.uid ?: ""

        val map = mapOf(
            "pageCount" to 10,
            "pageIndex" to pageIndex,
            "tokenType" to _mActivity.getString(R.string.wallet_cml),
            "txType" to transferParent?.currentStatus,
            "uid" to uid
//            "uid" to "11"
        )
//
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryTokenTxList)
            .success {
                parseDate(it)
            }.failure { onFailed() }
            .error { _, _ -> onFailed() }
            .build().post()
    }


    override fun parseDate(data: String?) {
//        super.parseDate(data)
        val obj = JSON.parseObject(data)
        val manager = PriceSetting.manager
        manager.pubTxSellPrice = obj["pubTxSellPrice"]?.toString() ?: ""
        manager.pubTxBuyPrice = obj["pubTxBuyPrice"]?.toString() ?: ""

        val isShowCmlPubValue = obj["isShowCmlPub"].toString().trim()

        isShowCmlPub = isShowCmlPubValue == "1"

        transferParent?.showSettingBtn(isShowCmlPub)

        val listStr = obj["list"]?.toString() ?: ""
        val array = JSON.parseArray(listStr, CMLTransferBean::class.java)
        loadListDate(array)
    }

    override fun onDestroy() {
        super.onDestroy()
        transferParent = null
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        when (view.id) {
            R.id.deleteTv -> {
                handDelete(item)
            }
            R.id.bottomTv -> {
                when (currentStatus) {
                    ICON_TRANSFER_SETTING_BUY -> {
                        start(CurrencyTransferBuyFragment.newInstance(item?.txid.toString()))
                    }

                    ICON_TRANSFER_SETTING_SELL -> {
                        start(CurrencyTransferSellFragment.newInstance(item?.txid.toString()))
                    }
                }
            }
        }


    }

    private var mAlertDialog: AlertDialog? = null

    private fun handDelete(item: CMLTransferBean?) {
        if (mAlertDialog != null) return
        mAlertDialog = AlertDialog.Builder(_mActivity)
            .setTitle("提示")
            .setMessage("确定删除吗？")
            .setOnDismissListener {
                mAlertDialog = null
            }
            .setPositiveButton(
                "确定"
            ) { _, which ->

                when (which) {
                    AlertDialog.BUTTON_POSITIVE -> {


                        val map = mapOf(
                            "txid" to item?.txid,
                            "uid" to item?.uid
                        )
                        RestClient.builder()
                            .url(R.string.deleteCmlTxByTxid)
                            .raw(JSON.toJSONString(map))
                            .success {
                                normalShortToast(_mActivity,R.string.delete_over)
//                                Toast.makeText(_mActivity, "删除成功", Toast.LENGTH_LONG).show()
                                mAdapter.remove(item)

                                if (mAdapter.data.isEmpty()) {
                                    onRefresh()
                                }

                            }
                            .error { _, msg ->
                                normalShortToast(_mActivity,msg)
//                                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
                            }.failure {
                                normalShortToast(_mActivity,"发送失败")
//                                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
                            }
                            .build().post()
                    }
                }

            }.create()

        mAlertDialog?.show()
    }
}